package com.dankegongyu.screenrecord;

import android.Manifest;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.Toast;


import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.danke.lib.permission.RxPermissions;

import io.reactivex.observers.DisposableObserver;

/**
 * 描述：权限activity
 * 作者：ChaoZheng on 2019-12-17 03:07
 * 邮箱：chaozheng@dankegongyu.com
 */
public class PermissionActivity extends FragmentActivity implements IOnRecorderStateChangeCallback {
    public static final int REQUEST_CODE_SCREEN_CAPTURE = 1000;
    public static final int REQUEST_CODE_OVERLAY_WINDOW = 1001;
    public static final String ACTION_FINISH_ACTIVITY = "finish";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        new RxPermissions(this)
                .request(permissions)
                .subscribe(new DisposableObserver<Boolean>() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @Override
                    public void onNext(Boolean isGranted) {
                        if (isGranted) {
                            // 浮窗权限
                            checkAlertWindowPermission();
                        } else {
                            cancel();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
        initConfig();
        registerFinishReceiver();
        bindRecordService();
    }

    /**
     * 绑定录屏服务
     */
    void bindRecordService() {
        // 启动录屏服务
        ScreenRecordService.start(this);
        // 绑定服务
        Intent intent = new Intent(this, ScreenRecordService.class);
        mServiceConnection = new RecordServiceConnection();
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }

    /* screen record */
    private MediaProjectionManager mProjectionManager;
    private RecordServiceConnection mServiceConnection;
    private IRecorderController mRecorderController;

    Handler mHandler;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SCREEN_CAPTURE: // 处理启动录屏
                if (resultCode == RESULT_OK) {
                    startRecordService(resultCode, data);
                    return;
                }
                cancel();
                break;
            case REQUEST_CODE_OVERLAY_WINDOW:  // 处理浮窗权限
                //https://blog.csdn.net/xudailong_blog/article/details/89364625
                if (mHandler == null) {
                    mHandler = new Handler(Looper.getMainLooper());
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            boolean nOpen = Settings.canDrawOverlays(PermissionActivity.this);
                            if (nOpen) {
                                //开启
                                startRecord();
                            } else {
                                //关闭
                                Toast.makeText(getApplicationContext(), "浮窗权限许可失败,浮窗功能将受影响!", Toast.LENGTH_LONG).show();
//                                cancel();
                            }
                        }
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            AppOpsManager appOpsMgr = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
                            int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), getPackageName());
                            if (mode == 1 || mode == 0) {
                                //权限已开起
                                startRecord();
                            } else if (mode == 2 || mode == 3) {
                                //权限已关闭
                                Toast.makeText(getApplicationContext(), "浮窗权限许可失败,浮窗功能将受影响!", Toast.LENGTH_LONG).show();
//                                cancel();
                            }
                            //此方法不可行，亲测华为8.0手机  未申请状态时  也返回1
                        }
                    }
                }, 500);
                //                if (!Settings.canDrawOverlays(this)) { // 许可了浮窗权限
                //                    Toast.makeText(getApplicationContext(), "浮窗权限许可失败,浮窗功能将受影响!", Toast.LENGTH_LONG).show();
                //                    cancel();
                //                    return;
                //                }
                startRecord();
                break;
        }
    }

    private void startRecordService(int resultCode, Intent data) {
        /* 获取屏幕采集的接口 */
        MediaProjection mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
        mRecorderController.setMediaProject(mMediaProjection);
        mRecorderController.startRecord();
    }

    private void cancel() {
        setResult(RESULT_CANCELED);
        finish();
    }

    /**
     * 查询或请求添加悬浮窗的权限
     * 没有授权则跳转至授权页面，请求授权
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void checkAlertWindowPermission() {
        if (Settings.canDrawOverlays(this)) {
            startRecord();
            return;
        }
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, REQUEST_CODE_OVERLAY_WINDOW);
    }

    private void startRecord() {
        // 通过系统服务获取MediaProjectionManager
        mProjectionManager = (MediaProjectionManager) getApplicationContext().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        // 发送录屏请求，在onActivityResult中处理请求结果
        if (mProjectionManager != null) {
            Intent intent = mProjectionManager.createScreenCaptureIntent();
            startActivityForResult(intent, REQUEST_CODE_SCREEN_CAPTURE);
        }
    }

    @Override
    public void onRecordStart() {

    }

    @Override
    public void onRecordUpdate(String time) {

    }

    @Override
    public void onRecordStop(boolean error) {

    }

    /**
     * 初始化尺寸信息
     */
    private void initConfig() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        // 通过DisplayMetrics得到屏幕宽高及dpi
        ScreenRecordConfig.width = metrics.widthPixels;
        ScreenRecordConfig.height = metrics.heightPixels;
        ScreenRecordConfig.dpi = metrics.densityDpi;
    }

    /* ServiceConnection */
    private class RecordServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mRecorderController = (IRecorderController) service;
            mRecorderController.setConfig(ScreenRecordConfig.width, ScreenRecordConfig.height, ScreenRecordConfig.dpi);
            // 设置回调，当服务端状态变化时，会回调相关方法
            mRecorderController.addRecordingCallback(PermissionActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mHandler) {
            mHandler.removeCallbacksAndMessages(null);
        }
        // 取消回调，
        if (mRecorderController != null) {
            // 在没有录屏，且无活动时结束服务
            if (!mRecorderController.isRecording()) {  // 在没有录屏的时候一并停止后台服务
                ScreenRecordService.stop(this);
            }
            mRecorderController.removeRecordingCallback(this);
            mRecorderController = null;
        }

        // 解绑服务
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
            mServiceConnection = null;
        }

        if (null != mReceiver) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
        }
    }

    DkFinishPermissionActivityReceiver mReceiver;

    private void registerFinishReceiver() {
        mReceiver = new DkFinishPermissionActivityReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                finish();
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_FINISH_ACTIVITY);
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, intentFilter);
    }
}
